/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package nio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import javafx.beans.value.WritableBooleanValue;

/**
 *
 * @author Administrator
 */
public class NIO {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://openhome.cc");
        ReadableByteChannel src = Channels.newChannel(url.openStream());
        WritableByteChannel dest = new FileOutputStream("index.html").getChannel();
        NIO.dump(src, dest);
        
        path();
        
        Path path1 = Paths.get("C:\\Users");
        Path path2 = Paths.get("Justin");
        Path path3 = path1.resolve(path2);//路径合并
        System.out.println(path3);
        
        Path path4 = Paths.get(System.getProperty("user.home"), "Documents", "Downloads");
        Path path5 = Paths.get("C:\\Users");
        Path path6 = path4.relativize(path5);//路径切换
        System.out.println(path6);
        
        System.out.println(path4.equals(path6));//比较路径是否相同
        System.out.println(path1.startsWith(path5));
        
        System.out.println(Files.exists(path4));//路径下的文档是否存在
        System.out.println(Files.isHidden(Paths.get("C:\\FHXVP")));//文件是否隐藏
        System.out.println(Files.isExecutable(Paths.get("C:\\AMTAG.BIN")));
        
        //获取文件属性
        getFileAttribute();
        
        Files.setAttribute(Paths.get("C:\\Users"), "dos:hidden", true);//修改文件隐藏属性
        
        long currentTime = System.currentTimeMillis();
        FileTime ft = FileTime.fromMillis(currentTime);
        Files.setAttribute(Paths.get("C:\\ckcore.txt"), "basic:lastModifiedTime", ft);//设置文件最后修改时间
        
        //Map<String, Object> attrs = Files.readAttributes(Paths.get("C:\\Users"), " size,lastModifiedTime,lastAccessTime");
        //System.out.println(attrs);
        
        //计算磁盘使用情况
        FileSystem fs = FileSystems.getDefault();
        for (FileStore store : fs.getFileStores()) {
            //print(store);
        }
        
        //文档复制
        Path srcPatn = Paths.get("C:\\src\\src.txt");
        Path destPath = Paths.get("C:\\dest\\dest.txt");
        Files.copy(srcPatn, destPath, StandardCopyOption.REPLACE_EXISTING);
        
        //将输出流写入到文档
        URL url1 = new URL("https://www.baidu.com/");
        Files.copy(url1.openStream(), destPath, StandardCopyOption.REPLACE_EXISTING);
        
        //Files.move(srcPatn, destPath, StandardCopyOption.ATOMIC_MOVE);
        //Files.createDirectory(destPath);
        
//        List<String> txt = Files.readAllLines(Paths.get("C:\\1.txt"));
//        String[] str = txt.get(0).split("\\s+");
//        Double d = Double.parseDouble(str[0]);
//        System.out.println(d);

        //获取根目录路径信息
        Iterable<Path> dirs = FileSystems.getDefault().getRootDirectories();
        dirs.forEach(System.out :: println);
        
        //查询目录下的文档
        try (DirectoryStream<Path> dirSys = Files.newDirectoryStream(Paths.get("C:\\Windows"))){
            List<String> files = new ArrayList<>();
            for (Path path : dirSys) {
                if (Files.isDirectory(path)) {
                    System.out.println(path.getFileName());
                } else {
                    files.add(path.getFileName().toString());
                }
            }
            files.forEach(System.out :: println);
        }
        
        //Files.walkFileTree(Paths.get("C:\\Users"), new ConsoleFileVisitor());
        
        try (Stream<Path> paths = Files.list(Paths.get("C:\\src"))){
            paths.forEach(System.out :: println);
        }
        
        try (Stream<Path> paths = Files.walk(Paths.get("C:\\src"))){
            paths.forEach(System.out :: println);
        }
        
        //根据条件查询目录下的文档
        try (DirectoryStream<Path> dirSys = Files.newDirectoryStream(Paths.get("C:\\Users\\All Users"), "*.{dat}")){
            dirSys.forEach(path -> System.out.println(path.getFileName()));
        }
        
        String glob = args.length == 0 ? "*" : args[0];
        Path userPath = Paths.get(System.getProperty("user.dir"));//取得当前路径
        try (DirectoryStream<Path> dir = Files.newDirectoryStream(userPath, glob)){
            dir.forEach(path -> System.out.println(path.getFileName()));
        }
        
        DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path entry) throws IOException {
                return (Files.isDirectory(entry));
            }
        };
        try (DirectoryStream<Path> d = Files.newDirectoryStream(Paths.get("C:\\Users\\All Users"), filter)){
            d.forEach(path -> System.out.println(path.getFileName()));
            
        }
        
        PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*");
        try (DirectoryStream<Path> dire = Files.newDirectoryStream(userPath)){
            dire.forEach(path -> {
                Path file = Paths.get(path.getFileName().toString());
                if (matcher.matches(file)) {
                    System.out.println(file.getFileName());
                }
            });
        }
    }
    
    
    public static void dump(ReadableByteChannel src, WritableByteChannel dest) throws IOException{
    
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try (ReadableByteChannel srcCH = src; WritableByteChannel destCH = dest){
         
            while (srcCH.read(buffer) != -1) {
                buffer.flip();
                destCH.write(buffer);
                buffer.clear();
            }
        }
    }
    
    public static void path(){
    
        Path path = Paths.get(System.getProperty("user.home"), "Documents", "Downloads");//文件夹不一定存在也可以
        System.out.println("toString" + path.toString());
        System.out.println(path.getFileName());
        System.out.println(path.getName(0));//最上层文件夹
        System.out.println(path.getNameCount());//4层文件夹
        System.out.println(path.subpath(0, 2));
        System.out.println(path.getParent());
        System.out.println(path.getRoot());
        path.forEach(System.out :: println);
    }
    
    public static void getFileAttribute() throws IOException{
    
        Path path = Paths.get("C:\\Xilinx");
        BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println(attrs.creationTime());
        System.out.println(attrs.lastAccessTime());
        System.out.println(attrs.lastModifiedTime());
        System.out.println(attrs.isDirectory());
        System.out.println(attrs.isOther());
        System.out.println(attrs.isRegularFile());
        System.out.println(attrs.isSymbolicLink());
        System.out.println(attrs.size());

    }
    
    public static void print(FileStore store) throws IOException{
    
        long total = store.getTotalSpace();
        long used = store.getTotalSpace() - store.getUnallocatedSpace();
        long usable = store.getUsableSpace();
        DecimalFormat format = new DecimalFormat("#,##,###");
        
        System.out.println(store.toString());
        System.out.println("总容量" + format.format(total) + " 字节");
        System.out.println("可用空间" + format.format(used) + " 字节");
        System.out.println("已用空间" + format.format(usable) + " 字节");
    }
}
